package com.yixun.qfbao.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * Created by Administrator on 2016/6/6.
 */
public class QiNiuUtil {

	private static final Logger logger = LoggerFactory.getLogger(QiNiuUtil.class);

	private static final Auth auth;
	private static final String ACCESS_KEY = "19MWcvu_DQadEbW2U-_DwNd_VYS2nHmiHVeRMyJd";
	private static final String SECRET_KEY = "41pEzhttF3vOiCSKy257h-WWmU7VmC9vbveUo4of";
	public static final String STORE_BUCKET;
	public static final String FILE_VIEWURL;
	// 创建上传对象
	private static final UploadManager uploadManager = new UploadManager();
	// 创建下载对象
	private static final BucketManager bucketManager;

	static {
		STORE_BUCKET = "qiaofang";
		FILE_VIEWURL = "https://image.qfstatic.com/";
		auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		bucketManager = new BucketManager(auth);// 实例化下载对象
	}
	
	/**
	 *	先判断源路径是否为七牛路径， 
	 *	如果不是，把原路径文件转换为七牛文件
	 * @param filePath
	 * @return
	 */
	public static String convertFileToQiniu(String filePath) {
		if(checkUrlBelongsQiniu(filePath)) {
			return filePath;
		}
		String fileKey = QiNiuUtil.getFileKey(filePath.substring(filePath.lastIndexOf(".")));
		try {
			byte[] urlbytes = UrlUtil.urlTobyte(filePath);
			upload(urlbytes, fileKey, QiNiuUtil.STORE_BUCKET);
			filePath = QiNiuUtil.FILE_VIEWURL + fileKey;
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return filePath;
	}
	
	/**
	 * 判断图片链接是否为qiniu图片链接
	 * @param url
	 * @return
	 */
	private static boolean checkUrlBelongsQiniu(String url) {
		if(url.startsWith(QiNiuUtil.FILE_VIEWURL)) 
			return true;
		return false;
	}

	public static String createUploadToken(String bucket) {
		return auth.uploadToken(bucket);
	}

	/**
	 * 单文件简单上传操作
	 * 
	 * @param filePath
	 *            上传文件的路径
	 * @param key
	 *            上传到七牛后保存的文件名
	 * @param bucket
	 *            要上传的空间
	 * @return 返回不为null表示上传成功，否则失败
	 * @throws IOException
	 */
	public static String upload(String filePath, String key, String bucket) throws IOException {
		try {
			// 调用put方法上传
			Response res = uploadManager.put(filePath, key, createUploadToken(bucket));

			return res.bodyString();
			// 打印返回的信息
		} catch (QiniuException e) {
			// 请求失败时打印的异常的信息
			logger.error("QiNiu upload error: {}", e);
		}
		return null;
	}

	public static String upload(byte[] data, String key, String bucket) throws IOException {
		try {
			// 调用put方法上传
			Response res = uploadManager.put(data, key, createUploadToken(bucket));

			return res.bodyString();
			// 打印返回的信息
		} catch (QiniuException e) {
			// 请求失败时打印的异常的信息
			logger.error("QiNiu upload error: {}", e);
		}
		return null;
	}
	
	/**
	 * 上传文件至七牛， 使用默认的桶
	 * @param data 文件数据
	 * @param fileSuffix 文件名后缀, 如 .png
	 * @return 上传至七牛之后的链接
	 * @throws IOException 
	 */
	public static String upload(byte[] data, String fileSuffix) throws IOException {
		String fileKey = getFileKey(fileSuffix);
		//将文件存储到七牛云
		upload(data, fileKey, QiNiuUtil.STORE_BUCKET);
		return QiNiuUtil.FILE_VIEWURL + fileKey;
	}

	/**
	 * 单文件简单上传操作 一律上传不做控制
	 * 
	 * @param filePath
	 *            上传文件的路径
	 * @param key
	 *            上传到七牛后保存的文件名
	 * @param bucket
	 *            要上传的空间
	 * @return 返回不为null表示上传成功，否则失败
	 * @throws IOException
	 */
	public static String uploadByMigration(String filePath, String key, String bucket) throws IOException {
		try {
			// 调用put方法上传
			Response res = uploadManager.put(filePath, key, createUploadToken(bucket));

			return res.bodyString();
		} catch (QiniuException e) {
			logger.error("uploadByMigration error: ", e);
		}
		return null;
	}

	/**
	 * 单文件删除操作
	 * 
	 * @param key
	 *            空间中保存的文件名
	 * @param bucket
	 *            空间名
	 * @return 返回success表示删除成功，否则失败
	 */
	public static String delete(String key, String bucket) {
		try {
			bucketManager.delete(bucket, key);
			return "success";
		} catch (QiniuException e) {
			logger.error("Qiniu delete file error: {}",e);
		}

		return null;
	}

	public static String delete(String key) {
		return delete(key, STORE_BUCKET);
	}

	/**
	 * 文件下载
	 * 
	 * @param key
	 *            保存的文件名
	 * @param bucket
	 *            上传的空间名
	 * @return
	 */
	public static String download(String key, String bucket) {
		StringBuilder sb = new StringBuilder("http://").append(bucket).append("/").append(key);
		// 创建下载链接 10分钟有效
		String downloadURL = auth.privateDownloadUrl(sb.toString(), 600);
		return downloadURL;
	}
	
	
	/**
	 * 根据后缀名产生一个文件key
	 * @param suffix
	 * @return
	 */
	public static String getFileKey(String suffix) {
		
		/*
		 *以channel开头标识为渠道王的文件，加上日期目录，uuid文件名加后缀。 
		 */
		StringBuilder builder=new StringBuilder("/channel/");
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

		builder.append(simpleDateFormat.format(System.currentTimeMillis())).append("/").append(UUID.randomUUID()).append(suffix);
		
		return builder.toString();
	}
	
}